/**
 *
 */
package com.dhcc.android.base.utils;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dhcc.android.base.R;

import java.util.Date;

/**
 * 录音
 *
 * @author pengling
 * @date 2015-6-26
 */
public class TakeVoiceUtil {
	private View childView;
	private Activity activity;
	long time1;
	long cha;
	long time2;
	public static MediaRecorder mediaRecorder = null;
	private MediaPlayer mPlayer = null;
	private TextView start_play;
	public static String voicePath = "", oldVoicePath = "";
	private String path;
	public static MyToastUtil myToastUtil = null;
	private TextView voice_time, voice_name;
	private LinearLayout delete_voice;
	public static boolean isDelete = false;
	public static String voiceName = "voice";
	public static boolean isruning = false;
	private LinearLayout stop_play;
	private Button take_voice;

	public TakeVoiceUtil(View childView, Activity activity, String path,
			String voiceName) {
		this.childView = childView;
		this.activity = activity;
		this.path = path;
		this.voiceName = voiceName;
	}

	private String voicePath_temp;

	public void initTakeVoice() {
		stop_play = (LinearLayout) childView.findViewById(R.id.stop_play);
		delete_voice = (LinearLayout) childView.findViewById(R.id.delete_voice);
		start_play = (TextView) childView.findViewById(R.id.start_play);
		take_voice = (Button) childView.findViewById(R.id.take_voice);
		voice_time = (TextView) childView.findViewById(R.id.voice_time);
		voice_name = (TextView) childView.findViewById(R.id.voice_name);
		myToastUtil = new MyToastUtil(activity, "正在录音...");

//		if (StringUtil.isEmpty(path)) {
//			path = DemandMainActivity.surveyDKIDPathNoData;
//		}
		oldVoicePath = path + "/" + voiceName;// 录音暂且只判断地址里有没有，未判断数据库里存在的情况
		// 录音是否为一份还是多份？？？一份：则再对名字进行控制；多份：则改成List的形式展示
		voicePath = path + "/" + FileUtil.getPhotoFileName(".mp3");// 旧的存在，就会将文件替换成新的，但是名称不改变
		if (FileUtil.isExistFile(oldVoicePath)
				&& StringUtil.isNotEmpty(voiceName)) {// 存在旧数据
			showVoiceData(-1, oldVoicePath);
		} else {
			oldVoicePath = voicePath;
			// voicePath = oldVoicePath;
			setBtnVisible(View.GONE);
		}
		voicePath_temp = voicePath;
		take_voice.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				// if (StringUtil.isFastDoubleClick(1000)) {
				// CommenUtil.toast("操作过快，请重试！", activity);
				// return false;
				// }else{
				int i = event.getAction();
				System.out.println("触摸事件："+i);
				switch (i) {
				case MotionEvent.ACTION_DOWN:
					if (!isruning) {
						isruning = true;
						time1 = new Date().getTime(); // 当前时间
						System.out.println("当前时间为1：" + time1);
						stopPlaying();
						myToastUtil.startToast();
						mediaRecorder = null;
						record();
						take_voice.setText("正在录音");
					}
					break;
				case MotionEvent.ACTION_CANCEL:
					System.out.println("CANCEL");
				case MotionEvent.ACTION_UP:
					System.out.println("isruning:" + isruning);
					if (isruning) { // 如果正在录音
						myToastUtil.stopToast();
						take_voice.setText("按住录音");
						Toast toast = Toast.makeText(activity, "终止录音...",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER_VERTICAL
								| Gravity.CENTER_HORIZONTAL, 0, 0);
						toast.show();
						mediaRecorder.stop(); // 停止录音
						mediaRecorder.release(); // 释放资源
						isruning = false;

						time2 = new Date().getTime(); // 当前时间
						System.out.println("当前时间为2：" + time2);
						cha = (time2 - time1) / 1000;

						if (cha <= 1) {
							CommenUtil.toast("时间太短了，请重新录", activity);
							FileUtil.deleteFile(voicePath);
							break;
						} else {
							FileUtil.renameFile(
									voicePath,
									voicePath_temp.replace(".mp3", "(" + cha
											+ ").mp3"));// 改文件名
							voicePath = voicePath_temp.replace(".mp3", "("
									+ cha + ").mp3");
							showVoiceData(cha, voicePath);
							initBeforeData();// 修改Map的值
						}

					}
					break;
				default:
					break;
				}
				// }

				return false;
			}
		});

		start_play.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (StringUtil.isFastDoubleClick(500)) {
					return;
				}
				if (!FileUtil.isExistFile(voicePath)
						&& !FileUtil.isExistFile(oldVoicePath)) {
					Toast.makeText(activity, "音频文件不存在，请先录音", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				Toast.makeText(activity, "播放录音...", Toast.LENGTH_SHORT).show();
				mPlayer = null;
				if (FileUtil.isExistFile(voicePath)) {
					System.out.println("play_start_new" + voicePath);
					startPlaying(voicePath);
				} else if (FileUtil.isExistFile(oldVoicePath)) {
					System.out.println("play_start_old" + oldVoicePath);
					startPlaying(oldVoicePath);
				}

			}
		});
		stop_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (StringUtil.isFastDoubleClick(500)) {
					return;
				}
				if (mPlayer == null) {
					Toast.makeText(activity, "您还没播放任何音频", Toast.LENGTH_SHORT)
							.show();
				} else {
					stopPlaying();
				}
			}
		});
		delete_voice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println("delete:" + voicePath);
				if (FileUtil.deleteFile(voicePath)) {
					isDelete = true;
//					String voiceSave = voicePath.replace(
//							DemandMainActivity.surveyPath, "");
//					String oldSave = oldVoicePath.replace(
//							DemandMainActivity.surveyPath, "");
//					DemandMainActivity.pathBefore = DemandMainActivity.pathBefore
//							.replace(voiceSave, "");
//					DemandMainActivity.pathBefore = DemandMainActivity.pathBefore
//							.replace(oldSave, "");// 含有mp3文件的都改删掉
//					((DemandMainActivity) activity).addMap.put(
//							((DemandMainActivity) activity).voiceKey,
//							DemandMainActivity.pathBefore);// 存储至数据库
//					setBtnVisible(View.GONE);
//					Toast.makeText(activity, "删除成功！", Toast.LENGTH_SHORT)
//							.show();
				}
			}
		});
	}

	// private String pathBefore = "";
	// 该方法 是用来是实现录音功能并保存到制定文件中
	public void record() {

		if (mediaRecorder == null) {
			mediaRecorder = new MediaRecorder(); // 判断是都为空 如果为空new 一个对象
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置输入源为麦克风
			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // 设置输出格式
			mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 设置音频的编码
																				// 默认
			// 创建一个临时文件来存储音频
			// path = Environment.getExternalStorageDirectory().getPath()
			// + "/test_Audio.mp3";
			isDelete = false;
			System.out.println("文件路径：" + voicePath);
			FileUtil.createFile(voicePath);
			mediaRecorder.setOutputFile(voicePath);

			// 为多份这里也得改？？？
			// mediaRecorder.getMaxAmplitude() 获取文件的大小
			try {
				mediaRecorder.prepare(); // 准备录音
			} catch (Exception e) {
				e.printStackTrace();
			}
			mediaRecorder.start(); // 开启录音
		}

	}

	private void startPlaying(String path) {
		try {
			mPlayer = new MediaPlayer();
			// 设置要播放的文件
			mPlayer.setDataSource(path);
			mPlayer.prepare();
			mPlayer.start();

		} catch (Exception e) {
			mPlayer.release();
			e.printStackTrace();
		}
	}

	// 停止播放
	private void stopPlaying() {
		if (mPlayer != null) {
			mPlayer.release();
			mPlayer = null;
			start_play.setEnabled(true);
			Toast.makeText(activity, "已终止播放", Toast.LENGTH_SHORT).show();

		}

	}

	/**
	 * 修改map的值
	 */
	private static String voiceSave_temp = "";

	private void initBeforeData() {
//		String voiceSave = voicePath.replace(DemandMainActivity.surveyPath, "");
//
//		if (StringUtil.isEmpty(DemandMainActivity.pathBefore)) {// 字段无数据
//			DemandMainActivity.pathBefore = voiceSave;// 为1417/voice.mp3
//		} else if (DemandMainActivity.pathBefore.contains("mp3")) {// 将其进行新旧替换
//			String oldSave = oldVoicePath.replace(
//					DemandMainActivity.surveyPath, "");
//			if (DemandMainActivity.pathBefore.contains(oldSave)) {
//				DemandMainActivity.pathBefore = DemandMainActivity.pathBefore
//						.replace(oldSave, voiceSave);
//			} else if (DemandMainActivity.pathBefore.contains(voiceSave_temp)) {
//				DemandMainActivity.pathBefore = DemandMainActivity.pathBefore
//						.replace(voiceSave_temp, voiceSave);
//			}
//			voiceSave_temp = voiceSave;
//		} else {
//			DemandMainActivity.pathBefore = DemandMainActivity.pathBefore + ","
//					+ voiceSave;
//		}
//		System.out.println("最后路径：" + DemandMainActivity.pathBefore);
//		((DemandMainActivity) activity).addMap.put(
//				((DemandMainActivity) activity).voiceKey,
//				DemandMainActivity.pathBefore);// 存储至数据库
	}

	private void showVoiceData(long cha, String name) {
		System.out.println("时间差为：" + cha + "秒" + ",文件路径：" + name);
		if (cha == -1 && name.contains(").mp3")) {// 没有值
			String cha_str = name.replace(").mp3", "");
			System.out.println("cha1:" + cha_str);
			cha_str = cha_str.substring(cha_str.lastIndexOf("(") + 1);
			System.out.println("cha2:" + cha_str);
			cha = Long.parseLong(cha_str);
		}
		setBtnVisible(View.VISIBLE);
		voice_time.setText("录制时间：" + cha + " 秒");
		voice_name.setText("文件名：" + name.replace(path, ""));
	}

	private void setBtnVisible(int visible) {
		delete_voice.setVisibility(visible);
		voice_name.setVisibility(visible);
		voice_time.setVisibility(visible);
		start_play.setVisibility(visible);
		stop_play.setVisibility(visible);
	}
}
